<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="聊天室ID" prop="cid">
        <el-input
          v-model="queryParams.cid"
          placeholder="请输入聊天室ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:chatroom:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:chatroom:remove']"
        >删除</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="chatroomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="聊天室ID" align="center" prop="cid" width="200" />
      <el-table-column label="聊天室名称" align="center" prop="title" />
      <el-table-column label="聊天室描述" align="center" prop="desc" show-overflow-tooltip />
      <el-table-column label="聊天室头像" align="center" prop="portrait" width="100">
        <template slot-scope="scope">
          <img 
            v-if="scope.row.portrait" 
            :src="getImageUrl(scope.row.portrait)" 
            style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover;"
            @error="handleImageError"
          />
          <el-avatar v-else :size="40" icon="el-icon-user-solid"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="聊天室状态" align="center" prop="state" width="180" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['system:chatroom:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:chatroom:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:chatroom:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改聊天室对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="聊天室ID" prop="cid">
          <el-input v-model="form.cid" placeholder="请输入聊天室ID" :disabled="form.cid && title.includes('修改')" />
        </el-form-item> -->
        <el-form-item label="聊天室名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入聊天室名称" />
        </el-form-item>
        <el-form-item label="聊天室描述" prop="desc">
          <el-input v-model="form.desc" type="desc" placeholder="请输入聊天室描述" />
        </el-form-item>
        <el-form-item label="聊天室头像" prop="portrait">
          <el-upload
            class="avatar-uploader"
            :action="upload.url"
            :headers="upload.headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept="image/*"
          >
            <img 
              v-if="form.portrait" 
              :src="getImageUrl(form.portrait)" 
              class="avatar" 
              @error="handleImageError"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div v-if="form.portraitPath" class="avatar-url-display">
            <el-button size="mini" type="text" @click="clearChatroomAvatar">清除头像</el-button>
          </div>
        </el-form-item>
        <el-form-item label="扩展信息" prop="extra">
          <el-input v-model="form.extra" type="textarea" placeholder="请输入扩展信息" />
        </el-form-item>
        <el-form-item label="聊天室状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择聊天室状态" clearable>
            <el-option label="公开" :value="0"></el-option>
            <el-option label="关闭" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
       
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!isView">确 定</el-button>
        <el-button @click="cancel">{{ isView ? '关 闭' : '取 消' }}</el-button>
      </div>
    </el-dialog>

    <!-- 查看聊天室详情对话框 -->
    <el-dialog 
    title="查看聊天室详情" 
    :visible.sync="viewOpen" 
    width="500px" 
    append-to-body
    @close="closeView">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="聊天室ID">
          {{ viewForm.cid }}
        </el-descriptions-item>
        <el-descriptions-item label="聊天室名称">
          {{ viewForm.title }}
        </el-descriptions-item>
        <el-descriptions-item label="聊天室描述">
          {{ viewForm.desc || '暂无描述' }}
        </el-descriptions-item>
        <el-descriptions-item label="聊天室头像">
          <img 
            v-if="viewForm.portrait" 
            :src="getImageUrl(viewForm.portrait)" 
            class="avatar" 
            @error="handleImageError"
            @click="previewImage(getImageUrl(viewForm.portrait))"
            style="cursor: pointer; width: 60px; height: 60px;"
          />
          <span v-else>暂无头像</span>
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeView">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listChatRoom, getChatRoom, delChatRoom, addChatRoom, updateChatRoom } from "@/api/zl/chatroom"
import request from "@/utils/request"
export default {
  name: "ChatRoom",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 聊天室表格数据
      chatroomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否为查看模式
      isView: false,
          // 查看表单数据
      viewForm: {},
      viewOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        chatroomId: null,
        chatroomTitle: null,
        chatroomDesc: null,
        chatroomPortrait: null,
        chatroomExtra: null
      },
      // 表单参数
      form: {
        chatroomId: null,
        chatroomTitle: null,
        chatroomDesc: null,
        chatroomPortrait: null,
        chatroomExtra: null
      },
      // 表单校验
      rules: {
        cid: [
          { required: true, message: "聊天室ID不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "聊天室名称不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询聊天室列表 */
    getList() {
      this.loading = true
      listChatRoom(this.queryParams).then(response => {
        this.chatroomList = response.rows
        this.total = parseInt(response.total) || 0
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.chatroomId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加聊天室"
      this.isView = false
    },
    /** 查看按钮操作 */
     handleView(row) {
      const chatroomId = row.cid
      getChatRoom(chatroomId).then(response => {
        this.viewForm = response.data
        this.viewOpen = true
      })
    },
    /** 关闭查看对话框 */
    closeView() {
      this.viewOpen = false
      this.viewForm = {}
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const chatroomId = row.cid
      getChatRoom(chatroomId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改聊天室"
        this.isView = false
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.title.includes("修改")) {
            updateChatRoom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addChatRoom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const chatroomIds = row.cid || this.ids
      this.$modal.confirm('是否确认删除聊天室编号为"' + chatroomIds + '"的数据项？').then(function() {
        return delChatRoom(chatroomIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
     /** 头像上传成功处理 */
        handleAvatarSuccess(res, file) {
          console.log('上传响应:', res);
          
          if (res.code === 200) {
            // 后端返回的是完整的阿里云OSS URL，需要清理空格和反引号
            let avatarUrl =  res.url;
            let avatarUrlPath =  res.fileName;

            
            // 清理URL中的空格、反引号和双引号
            if (avatarUrl) {
              avatarUrl = avatarUrl.trim().replace(/[`"]/g, '');
            }
            if (avatarUrlPath) {
              avatarUrlPath = avatarUrlPath.trim().replace(/[`"]/g, '');
            }
            
            this.form.portrait = avatarUrl;
            this.form.portraitPath = avatarUrlPath;

            this.$message.success('头像上传成功');
            
            // 强制更新视图
            this.$nextTick(() => {
              this.$forceUpdate();
            });
          } else {
            this.$message.error(res.msg || '上传失败');
          }
        },
        /** 头像上传前校验 */
        beforeAvatarUpload(file) {
          const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
          const isLt2M = file.size / 1024 / 1024 < 2

          if (!isJPG) {
            this.$modal.msgError('上传头像图片只能是 JPG/PNG/GIF 格式!')
          }
          if (!isLt2M) {
            this.$modal.msgError('上传头像图片大小不能超过 2MB!')
          }
          return isJPG && isLt2M
        },
        /** 清除头像 */
        clearChatroomAvatar() {
          if (this.form.portraitPath) {
            console.log('当前头像URL:', this.form.portraitPath);
            // 调用后端删除文件接口
            this.deleteFile(this.form.portraitPath).then(() => {
              this.form.portrait = null
              this.$modal.msgSuccess("头像已清除")
            }).catch(() => {
              // 即使删除失败也清除表单字段
              this.form.portraitPath = null
              this.$modal.msgSuccess("头像已清除")
            })
          }
        },
           /** 获取token */
        getToken() {
          return this.$store.getters.token
        },
        /** 删除文件 */
        deleteFile(fileName) {
          return request({
            url: '/common/delete',
            method: 'post',
            data: fileName,
            headers: {
              'Content-Type': 'text/plain'
            }
          })
        },
        /** 处理图片加载错误 */
        handleImageError(event) {
          // 设置默认头像
          event.target.src = require('@/assets/images/profile.jpg')
          // 或者可以隐藏图片：event.target.style.display = 'none'
        },
           /** 获取图片完整URL */
        getImageUrl(url) {
          if (!url) return ''
          // 清理URL中的空格和反引号
          url = url.trim().replace(/`/g, '');

          // 如果是OSS的完整URL，通过后端下载接口访问
          if (url.startsWith('https://') && url.includes('aliyuncs.com')) {
            return process.env.VUE_APP_BASE_API + '/common/download?fileName=' + encodeURIComponent(url) + '&delete=false'
          }
          
          // 如果已经是完整的HTTP/HTTPS URL，直接返回
          if (url.startsWith('http://') || url.startsWith('https://')) {
            return url
          }
          
          // 否则拼接BASE_API
          return process.env.VUE_APP_BASE_API + url
        }
  },
  computed: {
        /** 上传参数 */
        upload() {
          return {
            headers: { Authorization: "Bearer " + this.getToken() },
            url: process.env.VUE_APP_BASE_API + "/common/upload"
          }
        }
  }
}
</script>